package main

import (
	"context"
	"fmt"
	"time"

	"github.com/pkg/errors"
)

// 双向流通道
type BidirectionalChannel struct {
	// request 的 channel
	req chan int64
	//response 的 channel
	rsp chan int64
}

func NewBidirectionalChannel(bufSize int) *BidirectionalChannel {
	return &BidirectionalChannel{
		req: make(chan int64, bufSize),
		rsp: make(chan int64, bufSize),
	}
}
func (s *BidirectionalChannel) WriteReq(ctx context.Context, in int64) error {
	select {
	case <-ctx.Done():
		fmt.Println("WriteReq超时了")
		return errors.WithStack(ctx.Err())
	case s.req <- in:
	}
	return nil
}
func (s *BidirectionalChannel) ReadReq(ctx context.Context) (int64, error) {
	select {
	case <-ctx.Done():
		fmt.Println("ReadReq超时了")
		return -1, errors.WithStack(ctx.Err())
	case in := <-s.req:
		fmt.Println("将值下写入通道")
		return in, nil
	}
}
func main() {
	bc := NewBidirectionalChannel(16)
	ctx, cf := context.WithTimeout(context.Background(), time.Second*2)
	defer cf()
	go func() {
		for {
			i, err2 := bc.ReadReq(ctx)
			if err2 != nil {
				fmt.Println("ReadReq:", err2)
			} else {
				fmt.Println("ReadReq:", i)
			}
		}
	}()

	go func() {
		for {
			err := bc.WriteReq(ctx, 20)
			//	time.Sleep(time.Second * 1)
			if err != nil {
				fmt.Println("写请求报错", err)
			}
		}
	}()
	select {}
}
